package com.muli.muwai.controller;

import com.muli.muwai.api.Fenxiaofenke;
import com.muli.muwai.entity.*;
import com.muli.muwai.service.*;
import com.muli.muwai.util.POIUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;


@Slf4j
@RestController
@RequestMapping("/insert")
public class DataimportController {
    private static Logger logger = Logger.getLogger(DataimportController.class);
    @Resource
    IntfContracttSrevice contractSrevice;

    @Resource
    TraceTableService traceTableService;

    @Resource
    IntfPrincipalService intfPrincipalService;

    @Resource
    FinancetableService financetableService;

    @Resource
    ReturnCashService returnCashService;

    @Resource
    OrserSercive orserSercive;

    @Resource
    CostRevenueService costRevenueService;

    @Resource
    MarketingActivityService marketingActivity;

    @Resource
    ProductionCostService productionCostService;

    @Resource
    ClietService clietService;

    @Resource
    WeCatService weCatService;

    @Resource
    ProductionOrderService productionOrderService;

    @Resource
    StylistService stylistService;

    @Resource
    CompanyOrderService companyOrderService;

    @Resource
    CompanyService companyService;

    @Resource
    AreaMessageService areaMessageService;

    @Resource
    TargetService targetService;

    @Resource
    FinancingBudget financingBudget;

    @Resource
    ShareTrendService shareTrendService;

    @Resource
    UserTrendService userTrendService;

    @Resource
    PageAccessService pageAccessService;

    @Resource
    ProfessionDeparment professionDeparment;


    //TODO excel表格插入数据库  科目余额
    @PostMapping("/subject/excel")
    public ResponseEntity saveFinanceExcel(MultipartFile file) throws Exception {

        List<String[]> financeTable = POIUtils.readExcel(file);
        financetableService.importdata(financeTable);
        return ResponseEntity.ok().body("传入成功");

    }


    //TODO excel表格插入数据库 回款 要求为每月上传当月数据 由于给的测试数据为全月份所以走不通
    @PostMapping("/return/money/excel")
    public ResponseEntity returnMoney(MultipartFile file) throws Exception {
        List<String[]> returnMoney = POIUtils.readExcel(file);
        returnCashService.returnMoney(returnMoney);

        return ResponseEntity.ok().body("传入成功");
    }


    //TODO excel表格插入数据库 订单  要求为每月上传当月数据 由于给的测试数据为全月份所以走不通
    @PostMapping("/order/excel")
    public ResponseEntity<String> orderExcel(MultipartFile file) throws Exception {
        List<String[]> orderExcel = POIUtils.readExcel(file);

        orserSercive.orderExcel(orderExcel);

        return ResponseEntity.ok().body("传送成功");

    }


    //TODO excel表格插入数据  收入成本
    @PostMapping("/cost/revenue/excel")
    public void costRevenue(MultipartFile file) throws Exception {
        List<String[]> costRevenue = POIUtils.readExcel(file);
        costRevenueService.costRevenue(costRevenue);
    }


    //TODO  excel表格插入数据  生产成本 要求为上传单月数据其他月份数据不得传 测试数据所有月都有数据,故而报错
    @PostMapping("/production/cost/excel")
    public void productionCost(MultipartFile file) throws Exception {
        List<String[]> productionCost = POIUtils.readExcel(file);
        productionCostService.productionCost(productionCost);

    }


    //TODO excel表格插入数据  生产订单
    @PostMapping("/production/order/excel")
    public void productionOrder(MultipartFile file) throws IOException {
        List<String[]> productionOrder = POIUtils.readExcel(file);
        productionOrderService.productionorder(productionOrder);
    }


    //TODO excel表格插入数据  地理信息
    @PostMapping("/area/message/excel")
    public void areaMessage(MultipartFile file) throws IOException {
        List<String[]> areaMessage = POIUtils.readExcel(file);
        areaMessageService.areaMessage(areaMessage);
    }


    //TODO excel表格插入数据  目标对象
    @PostMapping("/target/excel")
    public void target(MultipartFile file) throws IOException {
        List<String[]> target = POIUtils.readExcel(file);
        targetService.target(target);
    }


    //TODO excel表格插入数据  财务预算
    @PostMapping("/fanance/excel")
    public void fanance(MultipartFile file) throws Exception {
        List<String[]> fanance = POIUtils.readExcel(file);
        financingBudget.fanance(fanance);
    }


    //TODO excel表格插入数据 分享趋势
    @PostMapping("/share/trend/excel")
    public ResponseEntity<String> shareTrend(MultipartFile file) throws Exception {
        List<String[]> sharetrend = POIUtils.readExcel(file);
        shareTrendService.sharetrend(sharetrend);
        return ResponseEntity.ok().body("已经发送成功");
    }


    //TODO excel表格插入数据 用户访问趋势
    @PostMapping("/user/trend/excel")
    public ResponseEntity<String> userTrend(MultipartFile file) throws IOException {
        List<String[]> userTrend = POIUtils.readExcel(file);
        userTrendService.userTrend(userTrend);
        return ResponseEntity.ok().body("已经发送成功");
    }


    //TODO excel表格插入数据 职能部门-公摊费率表
    @PostMapping("/profession/deparment/excel")
    public ResponseEntity<String> professionDeparment(MultipartFile file) throws IOException {
        List<String[]> professiondeparment = null;
        try {
            professiondeparment = POIUtils.readExcel(file);
        } catch (IOException e) {
            logger.error("职能部门-公摊费率excel数据读取失败");
        }

        try {
            professionDeparment.professiondeparment(professiondeparment);
        } catch (Exception e) {
            logger.error("职能部门-公摊费率excel数据插入失败");
        }

        return ResponseEntity.ok().body("已经发送成功");
    }


    /***********************************************************************/


    //TODO 客户跟踪(线索对象)
    @PostMapping("/save/tracetable")
    @Transactional(rollbackFor = Exception.class)
    @Scheduled(cron = "0 5 1 1/1 * ? ")
    public void saveTraceTable() {
        System.out.println("客户跟踪表任务开始");
        Integer offset = 0;
        Integer limit = 2000;
        Fenxiaofenke fenxiaofenke = new Fenxiaofenke();
        //提前删除数据  为插入做准备
        traceTableService.delectdata();
        while (true) {
            System.out.println("客户跟踪表任务正在运行");
            //调用方法获取数据
            List<TraceTable> traceTable = null;
            try {
                traceTable = fenxiaofenke.customerTracking(offset, limit);
            } catch (Exception e) {
                e.printStackTrace();
                logger.error("接口数据获取失败");
            }
            if (traceTable.size() == 0) {
                break;
            }
            offset += limit;
            //存入数据库
            traceTableService.saveTraceTable(traceTable);
        }
        logger.info("客户跟踪表任务结束");
    }


    //TODO 导入业绩-合同数据
    @PostMapping("/contract/import")
    @Scheduled(cron = "0 5 1 1/1 * ? ")
    @Transactional(rollbackFor = Exception.class)
    public void saveContrioller() {
        System.out.println("合同任务开始");
        Fenxiaofenke fenxiaofenke = new Fenxiaofenke();

        //删除九月1号之前的数据
        try {
            contractSrevice.deleteData();
        } catch (Exception e) {
            logger.error("合同删除9月1号之后的数据失败");
        }
        //定义初始数据
        Integer offset = 0;
        Integer limit = 1000;
        //调用方法
        while (true) {
            System.out.println("合同任务正在运行");
            //totalAndInfContract1 = fenxiaofenke.getTotalAndInfContract(offset, limit);
            List<IntfContract> totalAndInfContract1 = fenxiaofenke.getTotalAndInfContract(offset, limit);
            if (totalAndInfContract1.size() == 0) {
                break;
            }
            offset += limit;
            try {
                contractSrevice.Contractimport(totalAndInfContract1);
            } catch (Exception e) {
                logger.error("合同插入数据失败");
            }
        }
        logger.info("合同任务结束");
    }


    //TODO 获取负责人员信息
    @PostMapping("/principal/import")
    @Transactional(rollbackFor = Exception.class)
    @Scheduled(cron = "0 5 1 1/1 * ? ")
    public ResponseEntity<String> savePrincipal() {
        System.out.println("负责人员任务开始");
        Fenxiaofenke fenxiaofenke = new Fenxiaofenke();
        //删除数据
        intfPrincipalService.deleteData();
        //定义初始数据
        Integer offset = 0;
        Integer limit = 200;
        //调用方法
        List<IntfPrincipal> intfprincipalData = fenxiaofenke.getIntfprincipalData(offset, limit);
        intfPrincipalService.saveIntfPrincipalData(intfprincipalData);
        while (true) {
            System.out.println("负责人员任务正在运行");
            offset += limit;
            List<IntfPrincipal> intfprincipalData1 = null;
            try {
                intfprincipalData1 = fenxiaofenke.getIntfprincipalData(offset, limit);
            } catch (Exception e) {
                logger.error("负责人员接口获取数据失败");
            }
            if (intfprincipalData1.size() == 0) {
                break;
            }
            try {
                intfPrincipalService.saveIntfPrincipalData(intfprincipalData1);
            } catch (Exception e) {
                logger.error("负责人插入数据失败");
            }
        }
        logger.info("负责人员任务结束");
        return ResponseEntity.ok().body("发送成功");
    }


    //TODO 客户接口
    @PostMapping("/save/client")
    @Transactional(rollbackFor = Exception.class)
    @Scheduled(cron = "0 5 1 1/1 * ? ")
    public ResponseEntity<String> saveClient() {
        System.out.println("客户接口任务开始");
        Fenxiaofenke fenxiaofenke = new Fenxiaofenke();
        //先删除数据
        clietService.delectData();

        //定义初始数据
        Integer offset = 0;
        Integer limit = 1000;

        while (true) {
            System.out.println("客户任务正在运行");
            List<IntfClient> IntfClient = fenxiaofenke.getClint(offset, limit);
            if (IntfClient.size() == 0) {
                break;
            }
            offset += limit;
            clietService.saveClient(IntfClient);
        }
        logger.info("客户接口任务结束");
        return ResponseEntity.ok().body("发送成功");
    }


    //TODO 市场活动接口导入数据
    @PostMapping("/marketing/activity")
    @Transactional(rollbackFor = Exception.class)
    @Scheduled(cron = "0 0 1 1/1 * ? ")
    public ResponseEntity<String> saveMarketingActivity() {
        Thread thread = Thread.currentThread();
        System.out.println(thread.getName());
        System.out.println("市场活动任务开始");
        Fenxiaofenke fenxiaofenke = new Fenxiaofenke();
        //定义初始数据
        Integer offset = 0;
        Integer limit = 500;
        //删除全部数据
        marketingActivity.deleteData();

        while (true) {
            System.out.println("市场活动任务正在运行");
            List<IntfMarketingActivity> IntfMarketingActivity = null;
            try {
                IntfMarketingActivity = fenxiaofenke.getmarketingActivity(offset, limit);
            } catch (Exception e) {
                logger.error("市场活动接口获取数据失败");
            }
            if (IntfMarketingActivity.size() == 0) {
                break;
            }
            offset += limit;
            try {
                marketingActivity.saveMarketingActivity(IntfMarketingActivity);
            } catch (Exception e) {
                logger.error("市场活动接口插入数据失败");
            }
        }
        logger.info("市场活动任务结束");
        return ResponseEntity.ok().body("发送成功");
    }


    //TODO 业绩-集团下单
    @PostMapping("/save/company/order")
    @Scheduled(cron = "0 0 1 1/1 * ? ")
    @Transactional(rollbackFor = Exception.class)
    public ResponseEntity<String> saveCompanyOrder() {
        Thread thread = Thread.currentThread();
        System.out.println(thread.getName());
        System.out.println("业绩集团下单任务开始");
        Fenxiaofenke fenxiaofenke = new Fenxiaofenke();
        //定义初始数据
        Integer offset = 0;
        Integer limit = 1000;
        //删除9月1号之前的数据
        companyOrderService.deleteData();

        while (true) {
            System.out.println("业绩-集团正在运行");
            List<IntfCompanyOrder> companyorder = null;
            try {
                companyorder = fenxiaofenke.getCompanyOrder(offset, limit);
            } catch (Exception e) {
                logger.error("业绩-集团下单获取数据失败");
            }
            if (companyorder.size() == 0) {
                break;
            }
            offset += limit;
            try {
                companyOrderService.saveCompanyOrder(companyorder);
            } catch (Exception e) {
                logger.error("业绩-集团下单插入数据失败");
            }
        }
        logger.info("业绩集团任务结束");
        return ResponseEntity.ok().body("发送成功");
    }


    //TODO 服务项目
    @PostMapping("/save/service/company")
    @Transactional(rollbackFor = Exception.class)
    @Scheduled(cron = "0 0 1 1/1 * ? ")
    public ResponseEntity<String> saveServiceCompany() {
        Thread thread = Thread.currentThread();
        System.out.println(thread.getName());
        System.out.println("服务项目任务开始");
        Fenxiaofenke fenxiaofenke = new Fenxiaofenke();
        //定义初始数据
        Integer offset = 0;
        Integer limit = 1000;

        //删除数据在导入
        companyService.deleteData();

        while (true) {
            System.out.println("服务项目任务正在运行");
            List<IntfServiceProject> serviceCompany = null;
            try {
                serviceCompany = fenxiaofenke.getServiceCompany(offset, limit);
            } catch (Exception e) {
                logger.error("服务项目数据获取失败");
            }
            if (serviceCompany.size() == 0) {
                break;
            }
            offset += limit;
            try {
                companyService.saveServiceCompany(serviceCompany);
            } catch (Exception e) {
                logger.error("服务项目数据插入失败");
            }
        }
        logger.info("服务项目任务结束");
        return ResponseEntity.ok().body("发送成功");
    }


    //TODO 设计师档案

    @PostMapping("/save/designers")
    @Transactional(rollbackFor = Exception.class)
    @Scheduled(cron = "0 0 1 1/1 * ? ")
    public ResponseEntity<String> saveStylist() {
        System.out.println("设计师档案任务开始");
        Thread thread = Thread.currentThread();
        System.out.println(thread.getName());
        Fenxiaofenke fenxiaofenke = new Fenxiaofenke();
        //定义初始数据
        Integer offset = 0;
        Integer limit = 1000;
        //删除数据
        stylistService.deleteData();
        while (true) {
            List<IntfStylist> stylist = null;
            System.out.println("设计师档案任务正在运行");
            try {
                stylist = fenxiaofenke.getStylist(offset, limit);
            } catch (Exception e) {
                logger.error("设计师档案接口数据获取失败");
            }
            if (stylist.size() == 0) {
                break;
            }
            offset += limit;
            try {
                stylistService.saveStylist(stylist);
            } catch (Exception e) {
                logger.error("设计师档案接口数据插入失败");
            }
        }
        logger.info("设计师档案任务结束");
        return ResponseEntity.ok().body("发送成功");
    }


    //TODO 产品小程序-案例页面访问统计
    @GetMapping("/page/access")
    @Transactional(rollbackFor = Exception.class)
    @Scheduled(cron = "0 0 1 1/1 * ? ")
    public ResponseEntity<String> pageAccess() throws IOException {
        System.out.println("例页面访问统计任务开始");
        int current = 1;
        while (true) {
            List<IntfFinPageAccess> pageAccess = Fenxiaofenke.getPageAccess(current);
            System.out.println("例页面访问统计任务正在运行");
            if (pageAccess.size() == 0) {
                break;
            }
            pageAccessService.pageAccess(pageAccess);
            current += 1;
        }

        logger.info("例页面访问统计结束");
        return ResponseEntity.ok().body("已经发送成功");
    }


    //TODO 微信接口
    @PostMapping("/save/wechat")
    @Transactional(rollbackFor = Exception.class)
    @Scheduled(cron = "0 0 1 1/1 * ? ")
    public ResponseEntity<String> saveCat() {
        System.out.println("微信任务开始");
        Fenxiaofenke fenxiaofenke = new Fenxiaofenke();
        //定义初始数据
        Integer offset = 0;
        Integer limit = 1000;

        while (true) {
            System.out.println("微信任务正在运行");
            List<IntfWecat> intfWecats = null;
            try {
                intfWecats = fenxiaofenke.getwecat(offset, limit);
            } catch (Exception e) {
                logger.error("微信接口数据获取失败");
            }
            if (intfWecats.size() == 0) {
                break;
            }
            offset += limit;
            try {
                weCatService.saveCat(intfWecats);

            } catch (Exception e) {
                logger.error("微信插入数据获取失败");
            }
        }
        logger.info("微信任务结束");
        return ResponseEntity.ok().body("发送成功");
    }
}

